package com.lenovo.lcdm.dcm.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lenovo.lcdm.dcm.entity.Gv;
import com.lenovo.lcdm.dcm.service.GvService;
import com.lenovo.lcdm.integration.config.ConsumerMessageHandler;

import java.util.List;

public class GvConsumerHandler implements ConsumerMessageHandler {

    @Override
    public void handleMessage(String msg) {
        GvService gvService = SpringUtil.getBean(GvService.class);

        JSONObject jsonObject = JSONUtil.parseObj(msg);
        String sendTime = String.valueOf(jsonObject.get("sendTime") == null ? "" : jsonObject.get("sendTime"));
        if (ObjectUtil.isNotEmpty(jsonObject.get("gvs"))) {
            JSONArray jsonGvs = JSONUtil.parseArray(jsonObject.get("gvs"));
            List<Gv> gvs = jsonGvs.stream().map(obj -> {
                JSONObject jsonGv = JSONUtil.parseObj(obj);
                Gv gv = new Gv();
                gv.setGvItemId(jsonGv.get("gvItemID") == null ? "" : jsonGv.get("gvItemID").toString());
                gv.setGlobalValue(jsonGv.get("globalValue") == null ? "" : jsonGv.get("globalValue").toString());
                gv.setGlobalDescription(jsonGv.get("globalDescription") == null ? "" : jsonGv.get("globalDescription").toString());
                gv.setProductSegment(jsonGv.get("productSegment") == null ? "" : jsonGv.get("productSegment").toString());
                gv.setBusinessSegment(jsonGv.get("businessSegment") == null ? "" : jsonGv.get("businessSegment").toString());
                gv.setStatus(jsonGv.get("status") == null ? "" : jsonGv.get("status").toString());
                gv.setSendTime(sendTime);
                return gv;
            }).toList();
            if (CollectionUtil.isNotEmpty(gvs)) {
                List<Gv> list = gvService.lambdaQuery().ne(Gv::getSendTime, sendTime).list();
                if (CollectionUtil.isNotEmpty(list)) {
                    gvService.removeByIds(list.stream().map(Gv::getId).toList());
                }
                gvService.saveBatch(gvs);
            }
        }
    }
}
